package com.springboot.prac.pdf;

import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.*;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.*;

/**
 * @author : syl
 * @date : 2022/9/22 9:02
 * @desc :
 */
public class PdfUtils {

    /**
     * 生成pdf
     *
     * @param obj
     */
    public void createPdf(Object obj) {
        //模板路径
        String inputUrl = "D:\\word.pdf";
        //生成的文件路径
        String outputUrl = "D:\\out.pdf";
        //图片地址
        String pictureUrl = "D:\\1.jpg";
        byte[] bytes = null;

        OutputStream os = null;
        PdfStamper ps = null;
        PdfReader reader = null;
        //ByteArrayOutputStream bos = null;

        try {
            //图片的输入流
            FileInputStream fileInputStream = new FileInputStream(pictureUrl);
            bytes = new byte[fileInputStream.available()];
            fileInputStream.read(bytes);
            //图片转码
            BASE64Encoder encoder = new BASE64Encoder();
            os = new FileOutputStream(new File(outputUrl));
            //读取pdf表单
            reader = new PdfReader(inputUrl);
            //根据表单生成一个新的pdf文件
            ps = new PdfStamper(reader, os);
            //获取pdf表单
            AcroFields form = ps.getAcroFields();

            //bos = new ByteArrayOutputStream();

            //给表单中添加中文字体
            //BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            BaseFont bf = BaseFont.createFont("/font/simfang.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            form.addSubstitutionFont(bf);
            Map<String, Object> data = new HashMap<String, Object>();
            data.put("field1", "哈喽单车");
            data.put("field2", "男");
            data.put("field3", "999");
            data.put("field4", "徐州");

            // 插入图片
            insertImage(ps, form, "field6", "D:\\1.jpg");

            //遍历map集合，对应的填进去，本人测试过，如果没有与黑底的字段匹配的，那么那个部分数据填充就是空
            for (String key : data.keySet()) {
                form.setField(key, String.valueOf(data.get(key)));
            }
            ps.setFormFlattening(true);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                ps.close();
                reader.close();
                os.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void insertImage(PdfStamper pdfStamper, AcroFields acroFields, String field, String imageUrl) {
        try {
            List<AcroFields.FieldPosition> list = acroFields.getFieldPositions(field);
            Rectangle position = list.get(0).position;
            Image image = Image.getInstance(imageUrl);
            PdfContentByte overContent = pdfStamper.getOverContent(1);
            float left = position.getLeft();
            float bottom = position.getBottom();
            System.out.println(left);
            System.out.println(bottom);
            image.setAbsolutePosition(left, bottom);
            image.scaleToFit(position.getWidth(), position.getHeight());

            overContent.addImage(image);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * PDF文件转PNG图片，全部页数
     *
     * @param PdfFilePath  pdf完整路径
     * @param dstImgFolder 图片存放的文件夹
     * @param dpi          dpi越大转换后越清晰，相对转换速度越慢
     * @return 返回转换后图片集合list
     */
    public static List<File> pdfToImage(String PdfFilePath, String dstImgFolder, int dpi) {
        UUID uuid = UUID.randomUUID();
        String uuId = uuid.toString();
        System.out.println(uuId);
        File file = new File(PdfFilePath);
        //定义集合保存返回图片数据
        List<File> fileList = new ArrayList<File>();
        @SuppressWarnings("resource")//抑制警告
        PDDocument pdDocument = new PDDocument();
        try {
            //String imagePDFName = file.getName().substring(0, dot); // 获取图片文件名
            String imgFolderPath = null;
            if (dstImgFolder.equals("")) {
                imgFolderPath = dstImgFolder + File.separator + uuId;// 获取图片存放的文件夹路径
            } else {
                imgFolderPath = dstImgFolder + File.separator + uuId;
            }
            if (createDirectory(imgFolderPath)) {
                pdDocument = PDDocument.load(file);
                PDFRenderer renderer = new PDFRenderer(pdDocument);
                /* dpi越大转换后越清晰，相对转换速度越慢 */
                PdfReader reader = new PdfReader(PdfFilePath);
                int pages = reader.getNumberOfPages();
                System.out.println("pdf总共多少页-----" + pages);
                StringBuffer imgFilePath = null;
                for (int i = 0; i < pages; i++) {
                    String imgFilePathPrefix = imgFolderPath + File.separator + "study";
                    System.out.println("imgFilePathPrefix=====" + imgFilePathPrefix);
                    imgFilePath = new StringBuffer();
                    imgFilePath.append(imgFilePathPrefix);
                    imgFilePath.append("-");
                    imgFilePath.append(String.valueOf(i));
                    imgFilePath.append(".jpg");
                    File dstFile = new File(imgFilePath.toString());
                    BufferedImage image = renderer.renderImageWithDPI(i, dpi);
                    ImageIO.write(image, "png", dstFile);
                    fileList.add(dstFile);
                }
                System.out.println("PDF文档转PNG图片成功！");
                return fileList;
            } else {
                System.out.println("PDF文档转PNG图片失败：" + "创建" + imgFolderPath + "失败");
                return null;
            }
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    //创建文件夹
    private static boolean createDirectory(String folder) {
        File dir = new File(folder);
        if (dir.exists()) {
            return true;
        } else {
            return dir.mkdirs();
        }
    }

    //删除文件夹
    //param folderPath 文件夹完整绝对路径
    public static void delFolder(String folderPath) {
        try {
            delAllFile(folderPath); //删除完里面所有内容
            String filePath = folderPath;
            filePath = filePath.toString();
            java.io.File myFilePath = new java.io.File(filePath);
            myFilePath.delete(); //删除空文件夹
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //删除指定文件夹下所有文件
    //param path 文件夹完整绝对路径
    public static boolean delAllFile(String path) {
        boolean flag = false;
        File file = new File(path);
        if (!file.exists()) {
            return flag;
        }
        if (!file.isDirectory()) {
            return flag;
        }
        String[] tempList = file.list();
        File temp = null;
        for (int i = 0; i < tempList.length; i++) {
            if (path.endsWith(File.separator)) {
                temp = new File(path + tempList[i]);
            } else {
                temp = new File(path + File.separator + tempList[i]);
            }
            if (temp.isFile()) {
                temp.delete();

            }
            if (temp.isDirectory()) {
                delAllFile(path + "/" + tempList[i]);//先删除文件夹里面的文件
                delFolder(path + "/" + tempList[i]);//再删除空文件夹
                flag = true;
            }
        }
        return flag;
    }

    public static void main(String[] args) {
        PdfUtils pdfUtils = new PdfUtils();
        pdfUtils.createPdf("fff");

        pdfToImage("D:\\out.pdf", "D:\\image", 150);
    }
}
